package com.share.lottery.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.share.lottery.view.CustomToast;

import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

public class BaseApplication extends Application {
	private static BaseApplication mInstance;
	public boolean m_bKeyRight = true;
	// public BMapManager mBMapManager;
	private ProgressDialog pDialog;
//	private ImageLoader imgLoader;
	public static String SIMSERIAL;
	public static String LOCAL_MOBILE;
	public static final String strKey = "2HVGb79ZlfT2oGmSipNSSa1H";
	public static List<Activity> mListActivity;
	public static boolean isNeedRefesh = true;
	private static String msgTableName;
	private SharedPreferences sp;
	private ImageLoader imgLoader;

	public static BaseApplication getInstance() {
		return mInstance;
	}

	@Override
	public void onCreate() {
		mInstance = this;
		super.onCreate();

		getTelInfo();
//		JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
		// 初始化 JPush
//		JPushInterface.init(this);
		initImageLoadEnable();
	}

	
	/**
	 * 获取与本手机相关的一些东东
	 */
	private void getTelInfo() {
		// TODO Auto-generated method stub
		// 获取本机手机号码
		TelephonyManager tm = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE); // 创建电话管理并与手机建立连接
		// String deviceid = tm.getDeviceId(); //获取机器的deviceid(相当于手机设备的MEID)
		SIMSERIAL = tm.getSimSerialNumber(); // 获取sim卡的识别码(每张sim卡上面都会有)
		LOCAL_MOBILE = tm.getLine1Number(); // 获取本机的手机号码(现在有些机器获取不了…)
		if (LOCAL_MOBILE != null) {
			if (LOCAL_MOBILE.length() > 11) {
				LOCAL_MOBILE = LOCAL_MOBILE.substring(
						LOCAL_MOBILE.length() - 11, LOCAL_MOBILE.length());
			}
		} else {
			LOCAL_MOBILE = "";
		}
		if (SIMSERIAL == null || SIMSERIAL.equals("")) {
			SIMSERIAL = tm.getDeviceId();
		}
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}

	/**
	 * 获得机器码
	 * 
	 * @return
	 */
	public static String getTelCode() {
		TelephonyManager tm = (TelephonyManager) mInstance
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	/**
	 * 获得屏幕宽度
	 */
	public static int getScreenWidth() {
		WindowManager wm = (WindowManager) getInstance().getSystemService(
				Context.WINDOW_SERVICE);

		int width = wm.getDefaultDisplay().getWidth();// 屏幕宽度
		return width;
	}

	/**
	 * 获得屏幕宽度
	 */
	public static int getScreenHeight() {
		WindowManager wm = (WindowManager) getInstance().getSystemService(
				Context.WINDOW_SERVICE);

		int height = wm.getDefaultDisplay().getHeight();// 屏幕宽度
		return height;
	}

	public static void showToast(String msg) {

		CustomToast.makeText(mInstance, msg, Toast.LENGTH_SHORT);

	}

	public static void setActivity(Activity activity) {
		// TODO Auto-generated method stub
		if (mListActivity == null) {
			mListActivity = new ArrayList<Activity>();
		}
		mListActivity.add(activity);
	}

	public static void toHome() {
		if (mListActivity != null && mListActivity.size() > 0) {
			for (Activity activity : mListActivity) {
				if (activity != null && !activity.isFinishing()) {
					activity.finish();
				}
			}
			mListActivity.clear();
		}
	}

	public static void hideKeyBoard(Activity act) {
		if (act.getCurrentFocus() != null) {
			((InputMethodManager) act
					.getSystemService(act.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(act.getCurrentFocus()
							.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	public void showProgreessDialog(String msg) {

		if (pDialog == null) {
			pDialog = new ProgressDialog(this);
			pDialog.setMessage(msg);
		}
		pDialog.setMessage(msg);
		pDialog.show();
	}

	public void showProgreessDialog() {

		if (pDialog == null) {
			pDialog = new ProgressDialog(this);
			pDialog.setMessage("数据加载中..");
		}
		pDialog.setMessage("数据加载中..");
		pDialog.show();
	}

	public void dismissProgressDialog() {
		if (pDialog != null) {

			pDialog.dismiss();
		}
	}

	public static int getVersionCode() {
		int verCode = -1;
		try {
			verCode = mInstance.getPackageManager().getPackageInfo(
					mInstance.getPackageName(), 0).versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return verCode;
	}

	public static String getVerName() {
		String verName = "";
		try {
			verName = mInstance.getPackageManager().getPackageInfo(
					mInstance.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return verName;
	}

	public final static boolean isNetWorkConnected() {
		ConnectivityManager manager = (ConnectivityManager) mInstance
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo network = manager.getActiveNetworkInfo();
		if (network != null && network.isConnected()) {
			if (network.getState() == NetworkInfo.State.CONNECTED) {
				return true;
			}
		}
		return false;
	}

	public static void onExitApplication(final Activity context) {
		try {
			context.finish();
			Intent intent = new Intent();
			intent.setAction(context.getApplicationContext().getPackageName()
					+ ".ExitApplication");
			context.sendBroadcast(intent);

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					System.exit(0);
				}
			}, 100);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭掉所有的activity
	 */
	public static void exit() {
		// TODO Auto-generated method stub
		// 退出登录则直接退出
		getInstance().sendBroadcast(new Intent("finish"));
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				System.exit(0);
			}
		}, 100);
	}

	public static int getStatusBarHeight() {
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0, statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = getInstance().getResources()
					.getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}

//	public static String getMsgTableName() {
//		// TODO Auto-generated method stub
//		if (msgTableName == null) {
//			User user = Constants.getUserBean();
//			msgTableName = "msg_" + user.getARCHIVE_ID();
//		}
//
//		return msgTableName;
//	}

	public static void setMsgTableName(String msgtableName) {
		msgTableName = msgtableName;
	}

	/*************************************************************************************************/

	public boolean containsProperty(String key) {
		Properties props = getProperties();
		return props.containsKey(key);
	}

	public void setProperties(Properties ps) {
		set(ps);
	}

	public Properties getProperties() {
		return get();
	}

	public void setProperty(String key, String value) {
		set(key, value);
	}

	public String getProperty(String key) {
		return get(key);
	}

	public void removeProperty(String... key) {
		remove(key);
	}

	private final static String APP_CONFIG = "config";

	private void setProps(Properties p) {
		FileOutputStream fos = null;
		try {
			// 把config建在files目录下
			// fos = activity.openFileOutput(APP_CONFIG, Context.MODE_PRIVATE);

			// 把config建在(自定义)app_config的目录下
			File dirConf = getInstance().getDir(APP_CONFIG,
					Context.MODE_PRIVATE);
			File conf = new File(dirConf, APP_CONFIG);
			fos = new FileOutputStream(conf);

			p.store(fos, null);
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	public void set(Properties ps) {
		Properties props = get();
		props.putAll(ps);
		setProps(props);
	}

	public void set(String key, String value) {
		Properties props = get();
		props.setProperty(key, value);
		setProps(props);
	}

	public void remove(String... key) {
		Properties props = get();
		for (String k : key)
			props.remove(k);
		setProps(props);
	}

	public Properties get() {
		FileInputStream fis = null;
		Properties props = new Properties();
		try {
			// 读取files目录下的config
			// fis = activity.openFileInput(APP_CONFIG);

			// 读取app_config目录下的config
			File dirConf = getInstance().getDir(APP_CONFIG,
					Context.MODE_PRIVATE);
			fis = new FileInputStream(dirConf.getPath() + File.separator
					+ APP_CONFIG);

			props.load(fis);
		} catch (Exception e) {
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return props;
	}

	public String get(String key) {
		Properties props = get();
		return (props != null) ? props.getProperty(key) : null;
	}

	private static boolean isWifi(Context mContext) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	public void initImageLoadEnable() {
		sp = getSharedPreferences("setting", Context.MODE_PRIVATE);

		imgLoader = ImageLoader.getInstance();
		imgLoader.init(ImageLoaderConfiguration.createDefault(BaseApplication
				.getInstance()));
		boolean isOnlyInWifi = sp.getBoolean("pic_wifi", false);

		if (isOnlyInWifi && !isWifi(this)) {
			imgLoader.denyNetworkDownloads(true);
		} else {
			imgLoader.denyNetworkDownloads(false);
		}
	}

}
